/*
    BEEM is a videoconference application on the Android Platform.

    Copyright (C) 2009 by Frederic-Charles Barthelery,
                          Jean-Manuel Da Silva,
                          Nikita Kozlov,
                          Philippe Lago,
                          Jean Baptiste Vergely,
                          Vincent Veronis.

    This file is part of BEEM.

    BEEM is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    BEEM is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with BEEM.  If not, see <http://www.gnu.org/licenses/>.

    Please send bug reports with examples or suggestions to
    contact@beem-project.com or http://dev.beem-project.com/

    Epitech, hereby disclaims all copyright interest in the program "Beem"
    written by Frederic-Charles Barthelery,
               Jean-Manuel Da Silva,
               Nikita Kozlov,
               Philippe Lago,
               Jean Baptiste Vergely,
               Vincent Veronis.

    Nicolas Sadirac, November 26, 2009
    President of Epitech.

    Flavien Astraud, November 26, 2009
    Head of the EIP Laboratory.

*/
package com.beem.project.beem.ui;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.Dialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.awan.controller.UserItem;
import com.awan.controller.UserSearchItem;
import com.awan.utils.Constanta;
import com.awan.utils.GeneralStatic;
import com.awan.utils.HttpUtilsPost;
import com.beem.project.beem.BeemApplication;
import com.beem.project.beem.BeemService;
import com.beem.project.beem.R;
import com.beem.project.beem.service.aidl.IXmppFacade;
import com.beem.project.beem.utils.BeemBroadcastReceiver;

/**
 * This activity is used to add a contact.
 * @author nikita
 */
public class AddContact extends Activity {

    private static final Intent SERVICE_INTENT = new Intent();
    private static final String TAG = "AddContact";
    private final List<String> mGroup = new ArrayList<String>();
    private IXmppFacade mXmppFacade;
    private final ServiceConnection mServConn = new BeemServiceConnection();
    private final BeemBroadcastReceiver mReceiver = new BeemBroadcastReceiver();
    private final OkListener mOkListener = new OkListener();
    
    private ImageButton searchButton;
    private EditText searchText;
    private ListView searchView;
    private String userSearchUrl = Constanta.apiGetUserSearch;
    private SharedPreferences settings;
    private String myName;
    private UserListViewAdapter userAdapter;
    private ArrayList<UserSearchItem> userList;
    
    public static Context cntx;
    private Dialog loadingDialog;

    static {
    	SERVICE_INTENT.setComponent(new ComponentName("com.beem.project.beem", "com.beem.project.beem.BeemService"));
    }

    /**
     * Constructor.
     */
    public AddContact() {
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    	
		super.onCreate(savedInstanceState);
		
		cntx=this;
		loadingDialog = GeneralStatic.getDialogProgress(this);
		
		settings = PreferenceManager.getDefaultSharedPreferences(this);
		myName = settings.getString(BeemApplication.ACCOUNT_USERNAME_KEY, "");
		myName = myName.replace("@"+Constanta.chatDomain, "");
		
		setContentView(R.layout.addcontact);
		Button ok = (Button) findViewById(R.id.addc_ok);
		ok.setOnClickListener(mOkListener);
		this.registerReceiver(mReceiver, new IntentFilter(BeemBroadcastReceiver.BEEM_CONNECTION_CLOSED));
		
		searchText = (EditText)findViewById(R.id.editText1);
		
		searchButton = (ImageButton)findViewById(R.id.imageButton1);
		searchButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				String searchValue = searchText.getText().toString().trim();
				if(searchValue.equals("")){
					Toast.makeText(AddContact.this, "Please insert username or email", Toast.LENGTH_LONG).show();
				}else{
					getUserSearch(searchValue);
				}
			}
		});
		searchView = (ListView)findViewById(R.id.listView1);
		searchView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// TODO Auto-generated method stub
				UserSearchItem item = userList.get(arg2);
				String userName = item.username;
				showUserOptionDialog(userName);
			}
		});
		
    }
    
    private void showUserOptionDialog(final String userName){
    	Dialog dialog = new Dialog(this);
    	dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		dialog.setContentView(R.layout.right_menu_action);
		dialog.setTitle("Choose an Action");
		ListView actionList = (ListView)dialog.findViewById(R.id.rightMenuActionList);
		actionList.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
		actionList.setAdapter(new ArrayAdapter<String>(this, R.layout.listview_list, Constanta.searchActionTitle));
		dialog.show();
		actionList.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// TODO Auto-generated method stub
				switch(arg2){
				case 0:
					/*
					 * view profile
					 * */
					break;
				case 1:
					/*
					 * add as friend
					 * */
					
					// -> add to xmpp server
					String finalUsername = userName+"@"+Constanta.chatDomain;
					// -> add to API server					
					new Thread(){
						public void run(){
							/*
					    	 * params
					    	 * key, username
					    	 * */
							final Map<String, String> formParameters = new HashMap<String, String>();		
							formParameters.put("username", myName);	
							formParameters.put("friendname", userName);
							try {
								String friendAddRequest = HttpUtilsPost.post(Constanta.apiSetUserFriend, Constanta.requestHeaders(), formParameters, null);
								Log.e(TAG, "add contact response:"+friendAddRequest);
								JSONObject jsonResponse = new JSONObject(friendAddRequest);
								String status = jsonResponse.getString("STATUS");
								final String finalMessage;
								if(status.trim().equalsIgnoreCase("SUCCESS")){
									finalMessage = getString(R.string.AddCContactAdded);
								}else{
									finalMessage = jsonResponse.getString("MESSAGE");;
								}
								runOnUiThread(new Runnable() {											
									@Override
									public void run() {
										// TODO Auto-generated method stub
										Toast.makeText(AddContact.this, finalMessage, Toast.LENGTH_SHORT)
									    .show();													
									}
								});
							} catch (MalformedURLException e) {
								// TODO Auto-generated catch block
								Log.e(TAG, "error add contact response:"+e.getMessage());
								e.printStackTrace();
							} catch (ProtocolException e) {
								// TODO Auto-generated catch block
								Log.e(TAG, "error add contact response:"+e.getMessage());
								e.printStackTrace();
							} catch (IOException e) {
								// TODO Auto-generated catch block
								Log.e(TAG, "error add contact response:"+e.getMessage());
								e.printStackTrace();
							} catch (JSONException e) {
								// TODO Auto-generated catch block
								Log.e(TAG, "error add contact response:"+e.getMessage());
								e.printStackTrace();
							}finally{
								this.interrupt();
								finish();											
							}
						}
					}.start();
					//finish();
   // }
//}
					break;
				}
			}
		});
    }

    /* (non-Javadoc)
     * @see android.app.Activity#onStart()
     */
    @Override
    protected void onStart() {
    	super.onStart();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected void onResume() {
		super.onResume();
		bindService(new Intent(this, BeemService.class), mServConn, BIND_AUTO_CREATE);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected void onPause() {
		super.onPause();
		unbindService(mServConn);
    }

    /* (non-Javadoc)
     * @see android.app.Activity#onDestroy()
     */
    @Override
    protected void onDestroy() {
		super.onDestroy();
		this.unregisterReceiver(mReceiver);
    }

    /**
     * The ServiceConnection used to connect to the Beem service.
     */
    private class BeemServiceConnection implements ServiceConnection {

		/**
		 * Constructor.
		 */
		public BeemServiceConnection() {
		}
	
		//@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
		    mXmppFacade = IXmppFacade.Stub.asInterface(service);
		}
	
		//@Override
		public void onServiceDisconnected(ComponentName name) {
		    mXmppFacade = null;
		}
    }

    /**
     * Get the text of a widget.
     * @param id the id of the widget.
     * @return the text of the widget.
     */
    private String getWidgetText(int id) {
    	EditText widget = (EditText) this.findViewById(id);
    	return widget.getText().toString();
    }

    /**
     * Listener.
     */
    private class OkListener implements OnClickListener {

		/**
		 * Constructor.
		 */
		public OkListener() { }
	
		//@Override
		public void onClick(View v) {
			loadingDialog.show();
		    String login;
		    login = getWidgetText(R.id.addc_login);
		    if (login.length() == 0) {
		    	Toast.makeText(AddContact.this, getString(R.string.AddCBadForm), Toast.LENGTH_SHORT).show();
		    	return;
		    }
		    /*
		     * closed, because server is only have IP, fiuh.... (T_T)
		     * 
		     * boolean isEmail = Pattern.matches("[a-zA-Z0-9._%+-]+@(?:[a-zA-Z0-9-]+.)+[a-zA-Z]{2,4}", login);
		    if (!isEmail) {
				Toast.makeText(AddContact.this, getString(R.string.AddCContactAddedLoginError), Toast.LENGTH_SHORT)
				    .show();
				return;
		    }*/
		    String alias;
		    alias = getWidgetText(R.id.addc_alias);
		    if (getWidgetText(R.id.addc_group).length() != 0)
		    	mGroup.add(getWidgetText(R.id.addc_group));
		    try {
				if (mXmppFacade != null) {
				    if (mXmppFacade.getRoster().getContact(login) != null) {
						mGroup.addAll(mXmppFacade.getRoster().getContact(login).getGroups());
						Toast.makeText(AddContact.this, getString(R.string.AddCContactAlready), Toast.LENGTH_SHORT)
						    .show();
						return;
				    }
				    if (mXmppFacade.getRoster().addContact(login, alias, mGroup.toArray(new String[mGroup.size()])) == null) {
						Toast.makeText(AddContact.this, getString(R.string.AddCContactAddedError), Toast.LENGTH_SHORT)
						    .show();
						return;
				    } else {
						Toast.makeText(AddContact.this, getString(R.string.AddCContactAdded), Toast.LENGTH_SHORT)
						    .show();
						finish();
				    }
				}
		    } catch (RemoteException e) {
				Toast.makeText(AddContact.this, e.getMessage(), Toast.LENGTH_SHORT).show();
				loadingDialog.dismiss();
				Log.e(TAG, "Problem adding contact", e);
		    }
		}
    };
    
    private void getUserSearch(String searchKey){
    	
    	userList = new ArrayList<UserSearchItem>();
    	userAdapter = new UserListViewAdapter(AddContact.this, AddContact.this, R.layout.contactlistviewrow, userList);
    	searchView.setAdapter(userAdapter);
    	loadingDialog.show();
    	/*
    	 * params
    	 * key, username
    	 * */
		final Map<String, String> formParameters = new HashMap<String, String>();		
		formParameters.put("username", myName);	
		formParameters.put("key", searchKey);
		
		new Thread(){
			public void run(){
				try {
					final String profileRequest = HttpUtilsPost.post(userSearchUrl, Constanta.requestHeaders(), formParameters, null);
					Log.e(TAG, "profileRequest:"+profileRequest);
					runOnUiThread(new Runnable() {						
						@Override
						public void run() {
							// TODO Auto-generated method stub
							List<UserSearchItem> userItems = UserSearchItem.fromJsonArrayString(profileRequest);
							userAdapter.clear();
							for (UserSearchItem ui:userItems) {
								userAdapter.add(ui);
							}
							userAdapter.notifyDataSetChanged();
							//loadingDialog.dismiss();
						}
					});
				} catch (MalformedURLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (ProtocolException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}finally{
					runOnUiThread(new Runnable() {
						
						@Override
						public void run() {
							// TODO Auto-generated method stub
							loadingDialog.dismiss();
						}
					});
					this.interrupt();
				}
			}
		}.start();
    }
    private class UserListViewAdapter extends ArrayAdapter<UserSearchItem> {
    	
    	private ArrayList<UserSearchItem> items;
    	private LayoutInflater mInflater;
    	private Activity activity;

    	public UserListViewAdapter(Activity a, Context context, int textResourceId, ArrayList<UserSearchItem> items) {
    		super(context,textResourceId,items);
    		this.items=items;
    		this.activity=a;
    		mInflater=LayoutInflater.from(context);
    	}
    	
    	public View getView(int arg0, View convertView, ViewGroup arg2) {
    		// TODO Auto-generated method stub
    		UserSearchItemHolder holder;
    		if (convertView==null) {
    			convertView=mInflater.inflate(R.layout.contactlistviewrow, null);
    			holder=new UserSearchItemHolder();
    			holder.username=(TextView)convertView.findViewById(R.id.contactlistpseudo);
    			holder.avatar=(ImageView)convertView.findViewById(R.id.avatar);
    			convertView.setTag(holder);
    		} else {
    			holder=(UserSearchItemHolder)convertView.getTag();
    		}
    		UserSearchItem vi=items.get(arg0);
    		holder.username.setText(vi.username);
    		holder.avatar.setTag(vi.avatar);
    		
    		String avatarUrl = Constanta.apiPath+"/"+vi.avatar;
    		ContactList.imageLoader.DisplayImage(avatarUrl, holder.avatar, 100, 100);
    		
    		UserSearchItem di=new UserSearchItem();
    		di.username=vi.username;
    		di.userId=vi.userId;
    		di.fullName=vi.fullName;
    		di.gender=vi.gender;
    		//di.onLine=vi.onLine;
    		di.avatar=vi.avatar;
    		
    		convertView.setTag(R.id.detailTag, di);
    		return convertView;
    	}
    	
    }
    private class UserSearchItemHolder {
    	
    	TextView username;
    	ImageView avatar;

    }
}
